/**
 * Funciones para drag & drop para las lineas
 */
function draggableOnDragStartLine(e) {
}

function droptargetOnDragEnterLine(e) {
}

function droptargetOnDragLeaveLine(e) {
}

function droptargetOnDropLine(e) {
    var data = e.draggable.element.data();
    var lineId = data['lineId'];
    if( !existTeamLine( lineId ) ) {
        var teamLine = {
            id: kendo.guid(),
            line_id: lineId,
            line_name: data['lineName'],
            line_colour: data['lineColour'],
            group_id: appBosch.selectedTeam.id
        };
        addTeamLine(teamLine);
    }
}

function loadTeamLines(url) {
    var containerLinesMy = $('.container-lines .my');
    containerLinesMy.html('');
    $.getJSON(url, {}, function(teamLines) {
        appBosch.myTeamLines = [];
        teamLines.forEach(function(line) {
            appBosch.myTeamLines.push(line);
            var code = appBosch.templateTeamLine(line);
            containerLinesMy.append(code);
        });
    });
}

function loadRealLines(){
    /// Agregamos las lineas al contenedor todas
    var containerLinesAll = $('.container-lines .all');
    containerLinesAll.html('');
    appBosch.realLines.forEach(function(line) {
        var code = appBosch.templateLine(line);
        containerLinesAll.append(code);
    });
    
    //Drag & Drop para las lineas
    $(".line.draggable").kendoDraggable({
        hint: function() {
            return this.currentTarget.clone();
        },
        dragstart: draggableOnDragStartLine
    });
}

function loadVirtualLines(){
    if( !appBosch.KendoVirtualLines ){
        appBosch.KendoVirtualLines = $("#virtualLines").kendoDropDownList({
            autoBind: false,
            filter: "contains",
            placeholder: "Elige la Línea Virtual...",
            dataTextField: "text",
            dataValueField: "value",
            dataSource: [],
            change: function(e) {
                var vLineId = this.value();
                appBosch.tmpVLineId = vLineId;
                if( appBosch.currVLineId != vLineId ){
                    appBosch.dlgTemplate = kendo.template($("#dlgWindowTemplate").html());
                    var dlgWindow = $("#dlg").kendoWindow({
                        title: "Cambiar línea",
                        modal:true,
                        visible: false, //the window will not appear before its .open method is called
                        width: 350,
                        height: 90
                    }).data("kendoWindow");
                    dlgWindow.content(appBosch.dlgTemplate(appBosch.qMessages)); //send the row data object to the template and render it
                    dlgWindow.open().center();  

                    $("#yesButton").on('click',function(){
                        appBosch.currVLineId = appBosch.tmpVLineId;
                        $.getJSON(appBosch.urlUpdTeam,{
                            'lineId':appBosch.currVLineId,
                            'teamId':appBosch.currTeamId,
                            'areaId':appBosch.currAreaId
                        },function(){
                            setAreaByVirtualLine( appBosch.currVLineId );
                            appBosch.virtualLines   = appBosch.lines[appBosch.currAreaId].virtual;
                            appBosch.realLines      = appBosch.lines[appBosch.currAreaId].real;
                            appBosch.myTeamLines    = [];
                            $('.container-lines .my div.line').hide();
                            loadRealLines();
                        });
                        dlgWindow.close();
                    });
                    $("#noButton").on('click',function(){
                        
                        dlgWindow.close();
                    });
                    
                }//if area diferente
            }
        }).data("kendoDropDownList");
    }   
    var dataS = [];
    for( var areaId in appBosch.lines ){
        var virtualLines = appBosch.lines[areaId].virtual;
        for(var i = 0; i<virtualLines.length; i++){
            dataS.push({
                'value':virtualLines[i].value,
                'text': getAreaName(areaId) + ' - ' + virtualLines[i].text
            });
        }
    }
    appBosch.KendoVirtualLines.setDataSource( new kendo.data.DataSource({ data: dataS }) );
    if( appBosch.currVLineId ){
        appBosch.KendoVirtualLines.value( appBosch.currVLineId );
    }
}

function setAreaByVirtualLine( vLineId ){
    for( var areaId in appBosch.lines ){
        var virtualLines = appBosch.lines[areaId].virtual;
        for(var i = 0; i<virtualLines.length; i++){
            if( virtualLines[i].value === vLineId ){
                appBosch.currAreaId = areaId;
                break;
            }
        }
    }
}

function getAreaName(id){
    var areaName = '';
    for(var i=0;i<appBosch.areas.length;i++){
        if( appBosch.areas[i].area_id === id ){
            areaName = appBosch.areas[i].area;
            break;
        }
    }
    return areaName;
}

$(document).ready(function() {
    /// Cargamos los templates
    appBosch.templateLine = kendo.template($('#templateLine').html());
    appBosch.templateTeamLine = kendo.template($('#templateTeamLine').html());
    
    loadRealLines();

    $("#droptargetLine").kendoDropTarget({
        dragenter: droptargetOnDragEnterLine,
        dragleave: droptargetOnDragLeaveLine,
        drop: droptargetOnDropLine
    });

    $('div.container-lines').on('click', 'div.line i.destroy', function(e) {
        var divLine = $(e.target).parents('.line');
        divLine.hide();
        var id = divLine.data('id');
        var index = -1;
        for(var i = 0; i<appBosch.myTeamLines.length;i++){
            var teamUser = appBosch.myTeamLines[i];
            if( teamUser.id === id ){
                index = i;
                break;
            }
        }
        if( index !== -1 ){
            appBosch.myTeamLines.splice(index,1);
        }            
        $.getJSON(appBosch.urlTeamLinesDestroy,
                {
                    id: id
                });
    });
    
    $('div.container-lines').on('click', '.all div.line', function(e) {
        var divLine = $(this);
        var lineId  = divLine.data('lineId');
        if( !existTeamLine( lineId ) ) {
            var teamLine = {
                id: kendo.guid(),
                line_id: lineId,
                line_name: divLine.data('lineName'),
                line_colour: divLine.data('lineColour'),
                group_id: appBosch.selectedTeam.id
            };
            addTeamLine( teamLine );
        }        
    });
});

function existTeamLine(lineId){
    var exist = false;
    if (appBosch.myTeamLines === undefined) {
        appBosch.myTeamLines = [];
    }
    appBosch.myTeamLines.forEach(function(teamLine) {
        if (teamLine.line_id === lineId) {
            exist = true;
        }
    });    
    return exist;
}

function addTeamLine( teamLine ){
    $.getJSON( appBosch.urlTeamLinesCreate, { models: JSON.stringify([teamLine]) } );
    appBosch.myTeamLines.push(teamLine);
    var teamLineCode = appBosch.templateTeamLine(teamLine);
    $('.container-lines .my').append(teamLineCode);
}